package com.hui.ruiji.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hui.ruiji.common.CustomException;
import com.hui.ruiji.dto.SetmealDto;
import com.hui.ruiji.entity.Setmeal;
import com.hui.ruiji.entity.SetmealDish;
import com.hui.ruiji.mapper.SetmealMapper;
import com.hui.ruiji.service.SetmealDishService;
import com.hui.ruiji.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 新增套餐，同时需要保存套餐和菜品的关联关系
     *
     * @param setmealDto
     */
    @Override
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐的基本信息    setmeal
        this.save(setmealDto);
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        //保存套餐和菜品的关联信息  setmeal-dish
        setmealDishService.saveBatch(setmealDishes);
    }

    /**
     * 删除以及批量删除（停售的）
     *
     * @param ids
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {
        //查看是否选了
        if(ids.size() == 0){
            throw  new CustomException("没有勾选");
        }
        //查询状态，是否可以删除，停售状态
        LambdaQueryWrapper<Setmeal> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.in(Setmeal::getId, ids);
        queryWrapper.eq(Setmeal::getStatus, 1);

        int count = this.count(queryWrapper);
        if (count > 0) {
            //不能删除则抛出异常
            throw new CustomException("套餐正在售卖中,不能删除");
        }

        //删除 setmeal
        this.removeByIds(ids);

        //删除setealDish
        LambdaQueryWrapper<SetmealDish> queryWrapper1 = new LambdaQueryWrapper<>();
        queryWrapper1.in(SetmealDish::getSetmealId, ids);
        setmealDishService.remove(queryWrapper1);
    }
}
